import os from 'os'
import moment from 'moment'
import * as si from 'systeminformation'
import { createRequire } from "module"

const require = createRequire(import.meta.url)

export class stattools extends plugin {
  constructor() {
    super({
      name: 'System Status',
      dsc: '系统状态监控',
      event: 'message',
      priority: 5000,
      rule: [{
        reg: '^#状态$',
        fnc: 'status'
      }]
    })
  }

  formatFileSize(size) {
    if (!size) return '0B'
    const units = ['B', 'KB', 'MB', 'GB', 'TB']
    let index = 0
    while (size >= 1024 && index < units.length - 1) {
      size /= 1024
      index++
    }
    return `${size.toFixed(2)}${units[index]}`
  }

  formatTime(seconds) {
    const days = Math.floor(seconds / 86400)
    const hours = Math.floor((seconds % 86400) / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    
    let result = []
    if (days > 0) result.push(`${days}天`)
    if (hours > 0) result.push(`${hours}小时`)
    if (minutes > 0) result.push(`${minutes}分`)
    return result.length ? result.join('') : '0分'
  }

  async status(e) {
    try {
      // 获取系统信息
      const [cpu, currentLoad, mem, fsSize, osInfo, processes] = await Promise.all([
        si.cpu(),
        si.currentLoad(),
        si.mem(),
        si.fsSize(),
        si.osInfo(),
        si.processes()
      ])

      // Bot信息
      const bot = Bot[e.self_id] || Bot
      const botRuntime = this.formatTime(Date.now() / 1000 - bot.stat.start_time)
      
      // 插件信息
      const loader = (await import('../../lib/plugins/loader.js')).default
      const pluginCount = (loader.priority?.length || 0) + (loader.extended?.length || 0)
      const taskCount = loader.task?.length || 0

      // Node进程信息
      const nodeUsage = process.memoryUsage()
      
      // 磁盘使用率（主分区）
      const mainDisk = fsSize.find(fs => fs.mount === '/' || fs.mount === 'C:\\') || fsSize[0]
      
      // 构建状态信息
      const msg = [
        `【系统状态】${moment().format('MM-DD HH:mm:ss')}`,
        `━━━━━━━━━━━━━━━━`,
        `系统：${osInfo.distro} ${osInfo.release}`,
        `内核：${osInfo.kernel} ${osInfo.arch}`,
        `运行：${this.formatTime(os.uptime())}`,
        `━━━━━━━━━━━━━━━━`,
        `CPU：${cpu.manufacturer} ${cpu.brand}`,
        `核心：${cpu.physicalCores}核${cpu.cores}线程`,
        `使用：${currentLoad.currentLoad.toFixed(1)}%`,
        `━━━━━━━━━━━━━━━━`,
        `内存：${this.formatFileSize(mem.used)}/${this.formatFileSize(mem.total)} (${((mem.used/mem.total)*100).toFixed(1)}%)`,
        `Node：${this.formatFileSize(nodeUsage.rss)}`,
        `磁盘：${this.formatFileSize(mainDisk.used)}/${this.formatFileSize(mainDisk.size)} (${mainDisk.use.toFixed(1)}%)`,
        `━━━━━━━━━━━━━━━━`,
        `进程：${processes.all}个 (运行${processes.running})`,
        `Bot：${bot.nickname} (${bot.uin})`,
        `运行：${botRuntime}`,
        `插件：${pluginCount}个 (任务${taskCount})`,
        `━━━━━━━━━━━━━━━━`
      ]

      await e.reply(msg.join('\n'))
      return true
    } catch (error) {
      logger.error(`[stattools] 获取状态失败: ${error}`)
      e.reply('获取状态信息失败，请稍后再试')
      return false
    }
  }
}